"""
Created on 30-Nov-2009

@author: dexen
"""

from threading import Lock

from rpyc.utils import server

import dexen
from dexen.system.server.naming_manager import NamingManager
from dexen.system.base import service

#===============================================================================
# Globals
#===============================================================================
new_nodes = {}
dead_nodes = {}
lock = Lock()
name_mgr = None
node_mgr_addr = None
node_mgr_stime = None

masters = {}
slaves = {}
nodes = {}
#===============================================================================
# Service Class
#===============================================================================
class ResourceRegistryService(dexen.Service):
    def on_disconnect(self):
        if hasattr(self, "name"):
            self.unregister()
    
    def on_connect(self):
        print "I am connected"
    
    def register_node_mgr(self, stime, addr):
        global node_mgr_addr, node_mgr_stime
        print "node manager is registering with ", addr
        node_mgr_addr = addr
        node_mgr_stime = stime
    
    def get_node_mgr_addr(self):
        return node_mgr_addr
        
    def register_node(self, stime, addr):
        """
            Address is a tuple of (ip(str), port(int))
        """
        global new_nodes, name_mgr
        print "node with ", addr, "is registering"        
        with lock:
            self.name = name_mgr.get_name()
            new_nodes[self.name] = stime, addr
            nodes[self.name] = addr
            return self.name
    
    def register_master(self, name, addr):
        global masters
        print "master", name, "with", addr, "registering"
        with lock:
            masters[name] = addr
    
    def get_master_addr(self, name):
        with lock:
            return masters[name]
    
    def register_slave(self, name, addr):
        global slaves
        print "slave", name, "with", addr, "registering"
        with lock:
            slaves[name] = addr
    
    def get_slave_addr(self, name):
        with lock:
            return slaves[name]
    
    def unregister(self):
        global dead_nodes
        with lock:
            if new_nodes.has_key(self.name):
                del new_nodes[self.name]
            else:
                dead_nodes[self.name] = None
            name_mgr.release_name(self.name)
        
    def get_nodes(self):
        global new_nodes, dead_nodes
        with lock:
            ret = new_nodes, dead_nodes
            new_nodes = {}
            dead_nodes = {}
        return ret

def main():
    global name_mgr
    svr = server.ThreadedServer(ResourceRegistryService, 
                                port=service.REGISTRY_PORT,
                                protocol_config=service.default_config)
    name_mgr = NamingManager("NODE")
    svr.start()

if __name__ == "__main__":
    main()
